#include "StdAfx.h"
#include "IOCPRecvDataPackage.h"

CIOCPRecvDataPackage::CIOCPRecvDataPackage(void):
m_nCurrentHeadLen(0),
m_nCurrentLen(0),
m_nPackageLen(0),
m_cArrBuffer(NULL)
{
}

CIOCPRecvDataPackage::~CIOCPRecvDataPackage(void)
{
	Reset();
}

int CIOCPRecvDataPackage::Package(char* _cArrBuffer, int _nLen)
{
	if (m_nPackageLen <= 0)
	{
		return PackageHead(_cArrBuffer,_nLen);
	}else{
		return PackageContent(_cArrBuffer,_nLen);
	}
}

int CIOCPRecvDataPackage::PackageHead(char* _cArrBuffer, int _nLen)
{
	int nPackaged = 0;
	if (m_nCurrentHeadLen + _nLen < 4)
	{
		for (int i = 0; i != _nLen; ++i)
		{
			m_cHead[m_nCurrentHeadLen++] = _cArrBuffer[i];
		}
		nPackaged += _nLen;
		return nPackaged;
	}else{
		int nHeadLeft = 4 - m_nCurrentHeadLen;
		for (int i = 0; i != nHeadLeft; ++i)
		{
			m_cHead[m_nCurrentHeadLen++] = _cArrBuffer[i];
		}
		_nLen -= nHeadLeft;
		_cArrBuffer += nHeadLeft;
		nPackaged += nHeadLeft;
	}
	int* pLen = (int*)m_cHead;

	m_nPackageLen = *pLen;
	m_cArrBuffer = (char*)malloc(m_nPackageLen * sizeof(char));
	m_nCurrentLen = 0;

	if (_nLen > 0)
	{
		if (_nLen >= m_nPackageLen)
		{
			memcpy(m_cArrBuffer,_cArrBuffer,m_nPackageLen);
			nPackaged += m_nPackageLen;
			m_nCurrentLen = m_nPackageLen;
		}else{
			memcpy(m_cArrBuffer,_cArrBuffer,_nLen);
			nPackaged += _nLen;
			m_nCurrentLen = _nLen;
		}
	}

	return nPackaged;
}

int CIOCPRecvDataPackage::PackageContent(char* _cArrBuffer, int _nLen)
{
	int nPackaged = 0;
	if (_nLen > 0)
	{
		if (_nLen >= m_nPackageLen - m_nCurrentLen)
		{
			memcpy(m_cArrBuffer + m_nCurrentLen,_cArrBuffer,m_nPackageLen - m_nCurrentLen);
			nPackaged += m_nPackageLen - m_nCurrentLen;
			m_nCurrentLen = m_nPackageLen;
		}else{
			memcpy(m_cArrBuffer + m_nCurrentLen,_cArrBuffer,_nLen);
			nPackaged += _nLen;
			m_nCurrentLen += _nLen;
		}
	}

	return nPackaged;
}
